<?php
declare (strict_types=1);

namespace app\course\logic\record\admin;

use app\common\helper\util\Tool;
use app\course\model\record\admin\LearnCourseFinished;
use app\course\model\record\admin\LearnCourseRecord;
use app\course\model\record\admin\LearnDailyRecord;

/**
 * 学习记录逻辑类
 */
class LearnRecord extends LearnCourseRecord
{

    /**
     * 获取用户的学习记录概况
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-31
     *
     * @param int $user_id [description]
     * @return   [type]                                  [description]
     */
    public function getRecord(int $user_id)
    {
        $info = LearnDailyRecord::where('user_id', $user_id)->findOrEmpty();
        if ($info->isEmpty()) {
            $info = new \ArrayObject();
        } else {
            $today                       = strtotime(date('Y-m-d'));
            $info->total_learn_time      = ceil($info->total_learn_time / 60);
            // 今日学习时长、学习总时长
            if ($info->update_time < $today) {
                // 说明今日没有学习
                $info->today_learn_time = 0;
            } else {
                $info->today_learn_time = ceil($info->today_learn_time / 60);
            }

            // 连续学习天数
            if ($info->update_time + 86400 < $today) {
                $info->days = 0;
            }
            // 在学课程数
            $info->course_count = $this->where('user_id', $user_id)->count('DISTINCT course_id');
            // 完成课程数
            $info->finished_course_count = LearnCourseFinished::where('user_id', $user_id)->count();
        }

        return $info;
    }

    /**
     * 获取学习详情
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/1
     *
     * @param int $userId
     * @param int $courseId
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLearnInfo(int $userId, int $courseId)
    {
        // 查询所有学习记录
        $list = $this->withJoin(['sectionTitle'])
            ->where('__TABLE__.course_id', $courseId)
            ->where('__TABLE__.user_id', $userId)
            ->paginate($this->getListRows())->each(function ($item) {
                $item->total_learn_time = ceil($item->total_time / 60);
            });

        return $list;
    }

}
